/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import controlador.DBManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;


/**
 * Clase para poder modificar (añadir campos) a la tabla seleccionada
 *
 * @author Mª Luz García Rodríguez
 * @author Luis Massó Saiz
 */

public class JFrameModificar extends javax.swing.JFrame {

    private MdiPrueba padre;
    private DBManager BdManager;
    private String tabla;

    public void setTabla(String tabla) {
        this.tabla = tabla;
        jTNombreTabla.setText(tabla);
    }

    public void setBdManager(DBManager BdManager) {
        this.BdManager = BdManager;
    }

    public void setPadre(MdiPrueba padre) {
        this.padre = padre;
    }

    /**
     * Constructor JFrameModificar
     */
    public JFrameModificar() {
        initComponents();
    }

    /**
     * Constructor JFrameModificar
     * @param nombreTabla
     * @param padre
     * @param bd 
     */
    JFrameModificar(String nombreTabla, MdiPrueba padre, DBManager bd) {
        this();
        this.setTabla(nombreTabla);
        this.setPadre(padre);
        this.setBdManager(bd);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTNombreTabla = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTNombreCampo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jCBTipoDatos = new javax.swing.JComboBox();
        jChNulos = new javax.swing.JCheckBox();
        jBAgregarCampo = new javax.swing.JButton();
        jBTerminar = new javax.swing.JButton();
        jBcancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Nombre Tabla");

        jTNombreTabla.setEditable(false);

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));

        jLabel2.setText("Nombre campo");

        jLabel3.setText("Tipo Datos");

        jCBTipoDatos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "INTEGER", "BOOL", "DOUBLE", "FLOAT", "REAL", "CHAR", "TEXT", "VARCHAR", "BLOB", "NUMERIC", "DATETIME", "INTEGER (strict)", "REAL (strict)", "TEXT (strict)" }));

        jChNulos.setText("Permitir Nulo");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jTNombreCampo, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jCBTipoDatos, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(jChNulos)))
                .addGap(203, 203, 203))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jCBTipoDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTNombreCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jChNulos)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel2)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jBAgregarCampo.setText("Agregar campo");
        jBAgregarCampo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAgregarCampoActionPerformed(evt);
            }
        });

        jBTerminar.setText("Terminar");
        jBTerminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTerminarActionPerformed(evt);
            }
        });

        jBcancelar.setText("Cancelar");
        jBcancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBcancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTNombreTabla, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jBAgregarCampo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBTerminar)
                        .addGap(18, 18, 18)
                        .addComponent(jBcancelar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTNombreTabla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBAgregarCampo, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBcancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBTerminar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Método que agrega campos en la tabla sobre la que está actuando este JFrame
     * @param evt 
     */
    private void jBAgregarCampoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAgregarCampoActionPerformed
        String campo = jTNombreCampo.getText().replaceAll(" ", "_");
        String tipo = jCBTipoDatos.getSelectedItem().toString();
        String nulos = "";
        if (! jChNulos.isSelected()) {
            int opcion = JOptionPane.showConfirmDialog(null, "Si intenta añadir un campo NOT NULL, "+
                    "se le asignará por defecto a todas las filas ya introducidas el valor 1", "Confirmar NOT NULL", 
                    JOptionPane.YES_NO_OPTION);
            if (opcion == JOptionPane.YES_OPTION) {
                nulos = "NOT NULL DEFAULT 1";
            } 
        }
        
        
        String sql = "alter table " + tabla + " add column " + campo + " " + tipo + " " + nulos +";";
        try {
            BdManager.ejecutarInsercion(sql);
            LimpiarCampos();
            jTNombreTabla.setText(tabla);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error añadiendo el campo", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jBAgregarCampoActionPerformed

    /**
     * Método que cierra el formulario
     * @param evt 
     */
    private void jBTerminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTerminarActionPerformed
        this.dispose();
    }//GEN-LAST:event_jBTerminarActionPerformed

    /**
     * Método que cancela cuando hemos introducido algún dato (Los campos ya creados 
     * se quedarán en la tabla, ya que SQLite no permite eliminar columnas)
     * @param evt 
     */
    private void jBcancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBcancelarActionPerformed
        int opcion = JOptionPane.showConfirmDialog(null, "Los campos creadas permanecerán en la base de datos\n" +
                "¿Está seguro de que desea salir?", "¿Salir?", JOptionPane.OK_CANCEL_OPTION);
        if (opcion == JOptionPane.OK_OPTION) {
            LimpiarCampos();
            this.setVisible(false);
            padre.conectarBd(BdManager);
        }
    }//GEN-LAST:event_jBcancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameModificar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameModificar().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBAgregarCampo;
    private javax.swing.JButton jBTerminar;
    private javax.swing.JButton jBcancelar;
    private javax.swing.JComboBox jCBTipoDatos;
    private javax.swing.JCheckBox jChNulos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTNombreCampo;
    private javax.swing.JTextField jTNombreTabla;
    // End of variables declaration//GEN-END:variables

    /**
     * Método para limpiar todos los campos del formulario
     */
    private void LimpiarCampos() {
        jTNombreTabla.setText("");
        jTNombreCampo.setText("");
        jCBTipoDatos.setSelectedIndex(0);
        jChNulos.setSelected(false);
    }
}
